package com.hzz.web.app.user;

import com.hzz.api.user.IUserService;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.NoAuthorize;
import com.hzz.framework.config.EncryptConfig;
import com.hzz.framework.security.CryptoJSDES;
import com.hzz.framework.security.MD5;
import com.hzz.framework.util.*;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api("员工管理")
@RestController("apiStaffController")
@Slf4j
public class StaffController extends BaseController {
    private static final String acPrefix = "/api/staff/";
    @Autowired
    EncryptConfig encryptConfig;
    @Autowired
    IUserService staffService;
    @Autowired
    private EhcacheUtil cache;

    /**
     * <p> 信息分页 (未删除)。
     */
    //@RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "page/{pageNum}")
    @ApiOperation(value = "信息分页")
    public Response page(@RequestBody UserDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("page.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            UserDto staffDto = JwtUtil.getSubject(UserDto.class);
            dto.setStaffId(staffDto.getId());
            dto.setIsSuper(staffDto.getIsSuper());
            result.data = getPageDto(staffService.findDataIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    //@RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
    @ApiOperation(value = "详情-根据id")
    public Response info(@PathVariable("id") Long id) {
        log.info("info.........");
        Response result = new Response();
        try {
            UserDto staffDto = new UserDto();
            staffDto.setId(id);
            result.data = staffService.findDataById(staffDto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 个人信息更新
     */
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "ownupdate")
    @ALogOperation(type = "修改", desc = "个人信息更新")
    @ApiOperation(value = "信息保存")
    public Response ownupdate(@RequestBody UserDto dto) {
        log.info("ownupdate.........");
        Response result = new Response(0, "success");
        try {
            UserDto staff = JwtUtil.getSubject(UserDto.class);
            dto.setId(staff.getId());
            dto.setCreateId(staff.getId());
            result.data = staffService.updateData(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 个人密码修改
     */
    @RequestMapping(method = {RequestMethod.POST}, value = acPrefix + "update/ownpassword")
    @ALogOperation(type = "修改", desc = "个人密码修改")
    @ApiOperation(value = "密码修改")
    public Response ownpassword(@RequestBody UserDto dto) {
        log.info("ownpassword.........");
        Response result = new Response(0, "success");
        try {
            if (dto == null || ValidatorUtil.isNullEmpty(dto.getOriginalPassword()) || ValidatorUtil.isNullEmpty(dto.getNewPassword()) || ValidatorUtil.isNullEmpty(dto.getConfirmPassword())) {
                return Response.error("提交数据不完整!");
            }
            if (!dto.getNewPassword().equals(dto.getConfirmPassword())) {
                throw new RuntimeException("两次密码不一致!");
            }
//           originalPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.originalPassword).toString()),
            if (ValidatorUtil.notEmpty(dto.getOriginalPassword())) {
                dto.setOriginalPassword(CryptoJSDES.desDecrypt(dto.getOriginalPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
//           newPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.newPassword).toString()),
            if (ValidatorUtil.notEmpty(dto.getNewPassword())) {
                dto.setNewPassword(CryptoJSDES.desDecrypt(dto.getNewPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
//           confirmPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.confirmPassword).toString())
            if (ValidatorUtil.notEmpty(dto.getConfirmPassword())) {
                dto.setConfirmPassword(CryptoJSDES.desDecrypt(dto.getConfirmPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
            dto.setId(JwtUtil.getSubject(UserDto.class).getId());
            result.message = staffService.updatePassword(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 用户在线心跳
     */
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "heart/beat")
    @ApiOperation(value = "用户在线心跳")
    public Response heartbeat() {
        log.info("heartbeat.........");
        Response result = new Response(0, "success");
        try {
            UserDto staff = JwtUtil.getSubject(UserDto.class);
            if (staff != null && (CommonConstant.TYPES_各河长.indexOf(staff.getType()) != -1)) {
                // 河长在线统计
                OnLineCacheUtil.set(staff.getAccount(), 1, CommonConstant.ONLINE_CACHE_TIMEOUT);
            }
            result.data = OnLineCacheUtil.size();
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    //@RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "river")
    @ApiOperation(value = "河道-水库-渠道")
    public Response river() {
        log.info("river.........");
        Response result = new Response();
        try {
            UserDto staffDto = JwtUtil.getSubject(UserDto.class);
            result.data = staffService.findRiverDataByUserId(staffDto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }


    /**
     * <p> 信息分页 (未删除)。
     */
    //@RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "syncpage/{pageNum}")
    @ApiOperation(value = "信息分页")
    @NoAuthorize
    public Response syncpage(@ModelAttribute UserDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("syncpage.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            result.data = getPageDto(staffService.findDataIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
}
